// 商品数据 - 这里先定义5种作为示例，您可以补充完整30种
const products = [
    { id: 818240, name: "培根乳酪洋芋贝果", perTray: 12, layersNeeded: 1, program: 1 },
    { id: 818258, name: "香蕉软糕", perTray: 24, layersNeeded: 1, program: 1 },
    { id: 818241, name: "蓝莓乳酪贝果", perTray: 12, layersNeeded: 1, program: 1 },
    { id: 818259, name: "可丽露", perTray: 40, layersNeeded: 1, program: 1 },
    { id: 818242, name: "全能乳酪贝果", perTray: 12, layersNeeded: 1, program: 1 },
    { id: 818271, name: "葡式蛋挞", perTray: 24, layersNeeded: 1, program: 1 },
    { id: 818249, name: "酸种丹麦碱水结", perTray: 6, layersNeeded: 1, program: 1 },
    { id: 818263, name: "切达干酪墨西哥胡椒夹心比萨甜甜圈", perTray: 12, layersNeeded: 1, program: 1 },
    { id: 820250, name: "蓝莓桑葚欧包", perTray: 12, layersNeeded: 1, program: 2 },
    { id: 820249, name: "无花果乳酪欧包", perTray: 12, layersNeeded: 1, program: 2 },
    { id: 820251, name: "岩烧榴莲芝士欧包", perTray: 9, layersNeeded: 1, program: 2 },
    { id: 818252, name: "手撕包", perTray: 12, layersNeeded: 2, program: 2 },
    { id: 820252, name: "红丝绒蔓越莓欧包", perTray: 9, layersNeeded: 1, program: 2 },
    { id: 818253, name: "斯佩尔特红菜头夏巴达", perTray: 6, layersNeeded: 1, program: 2 },
    { id: 818254, name: "千层吐司", perTray: 12, layersNeeded: 2, program: 2 },
    { id: 818251, name: "法式蒜香牛油法棍", perTray: 8, layersNeeded: 1, program: 3 },
    { id: 818255, name: "亚麻籽蔓越莓包", perTray: 6, layersNeeded: 1, program: 3 },
    { id: 818256, name: "黑麦葡萄包", perTray: 6, layersNeeded: 1, program: 3 },
    { id: 818257, name: "黑麦核桃包", perTray: 6, layersNeeded: 1, program: 3 },
    { id: 818267, name: "法式巧克力面包", perTray: 12, layersNeeded: 1, program: 4 },
    { id: 818265, name: "葡萄干面包", perTray: 9, layersNeeded: 1, program: 4 },
    { id: 818266, name: "瑞士葡萄干布里欧修", perTray: 12, layersNeeded: 1, program: 4 },
    { id: 818274, name: "苹果派", perTray: 8, layersNeeded: 1, program: 4 },
    { id: 818272, name: "黄油牛角包", perTray: 12, layersNeeded: 1, program: 4 },
    { id: 818273, name: "巧克力榛子牛角包", perTray: 12, layersNeeded: 1, program: 4 },
    { id: 818275, name: "肉桂卷", perTray: 12, layersNeeded: 1, program: 4 },
    { id: 818279, name: "枫糖碧根果酥", perTray: 12, layersNeeded: 1, program: 4 }
];

// 烤箱配置
const ovenConfig = {
    ovenCount: 2,
    chambersPerOven: 2,
    chamberLayers: [5, 10] // 第一个炉室5层，第二个10层
};

// 页面加载时创建按程序分组的输入框
document.addEventListener('DOMContentLoaded', function() {
    const inputContainer = document.getElementById('product-inputs');
    
    // 按程序分组
    const programs = {};
    products.forEach(product => {
        if (!programs[product.program]) {
            programs[product.program] = [];
        }
        programs[product.program].push(product);
    });
    
    // 为每个程序创建分组
    Object.keys(programs).forEach(program => {
        const programDiv = document.createElement('div');
        programDiv.className = `program-group program-${program}`;
        
        // 程序标题
        const headerDiv = document.createElement('div');
        headerDiv.className = 'program-header';
        headerDiv.textContent = `烘烤程序 ${program}`;
        programDiv.appendChild(headerDiv);
        
        // 程序内容区
        const contentDiv = document.createElement('div');
        contentDiv.className = 'program-content';
        
        // 添加该程序下的所有商品
        programs[program].forEach(product => {
            const productDiv = document.createElement('div');
            productDiv.className = 'product-input';
            
            const label = document.createElement('label');
            label.textContent = product.name;
            
            const input = document.createElement('input');
            input.type = 'number';
            input.min = '0';
            input.value = '0';
            input.id = `product-${product.id}`;
            
            productDiv.appendChild(label);
            productDiv.appendChild(input);
            contentDiv.appendChild(productDiv);
        });
        
        programDiv.appendChild(contentDiv);
        inputContainer.appendChild(programDiv);
    });
    
    // 绑定计算按钮事件
    document.getElementById('calculate-btn').addEventListener('click', calculateSchedule);
    // 添加清零按钮事件
    document.getElementById('reset-btn').addEventListener('click', function() {
        products.forEach(product => {
            const input = document.getElementById(`product-${product.id}`);
            input.value = '0';
        });
    });
});

// 计算排产 - 多批次版本
// 计算排产 - 最终修正版
// 计算排产 - 修复批次分配版本
// 计算排产 - 优化炉室分配版本
function calculateSchedule() {
    // 获取输入数量(直接作为托盘数)
    const inputs = {};
    products.forEach(product => {
        const input = document.getElementById(`product-${product.id}`);
        inputs[product.id] = parseInt(input.value) || 0;
    });
    
    // 准备需求数据
    const allRequirements = products.map(product => {
        const trays = inputs[product.id];
        return {
            ...product,
            quantity: trays * product.perTray,
            traysNeeded: trays,
            remainingTrays: trays,
            layersPerTray: product.layersNeeded
        };
    }).filter(product => product.traysNeeded > 0);
    
    // 按烘烤程序分组并计算每个程序的总层数需求
    const programs = {};
    allRequirements.forEach(product => {
        if (!programs[product.program]) {
            programs[product.program] = {
                products: [],
                totalLayers: 0
            };
        }
        programs[product.program].products.push(product);
        programs[product.program].totalLayers += product.traysNeeded * product.layersNeeded;
    });
    
    // 存储所有批次结果
    const allBatches = [];
    let hasUnallocated = true;
    
    while (hasUnallocated) {
        const currentBatchOvens = initializeOvens();
        let allocatedInBatch = false;
        
        // 按程序总层数降序处理(先处理大程序)
        Object.keys(programs)
            .sort((a, b) => programs[b].totalLayers - programs[a].totalLayers)
            .forEach(program => {
                const programData = programs[program];
                if (programData.totalLayers <= 0) return;
                
                // 尝试将程序分配到最优炉室
                if (tryAllocateProgramOptimally(programData, currentBatchOvens)) {
                    allocatedInBatch = true;
                }
            });
        
        if (allocatedInBatch) {
            allBatches.push(currentBatchOvens);
            // 更新程序总层数
            updateProgramLayers(programs);
        }
        
        hasUnallocated = checkUnallocated(programs);
    }
    
    displayBatchResults(allBatches, allRequirements);
}

// 最优分配策略
function tryAllocateProgramOptimally(programData, ovens) {
    const program = programData.products[0].program;
    const totalNeededLayers = programData.products.reduce(
        (sum, p) => sum + (p.remainingTrays * p.layersPerTray), 0);
    
    // 策略1: 优先尝试将整个程序放入单个小炉室(如果能放下)
    if (totalNeededLayers <= 5) {
        for (const oven of ovens) {
            const smallChamber = oven.chambers.find(c => c.maxLayers === 5);
            if (smallChamber && smallChamber.program === null) {
                return allocateWholeProgram(programData, smallChamber);
            }
        }
    }
    
    // 策略2: 尝试将整个程序放入单个大炉室(如果能放下)
    if (totalNeededLayers <= 10) {
        for (const oven of ovens) {
            const largeChamber = oven.chambers.find(c => c.maxLayers === 10);
            if (largeChamber && largeChamber.program === null) {
                return allocateWholeProgram(programData, largeChamber);
            }
        }
    }
    
    // 策略3: 分散分配到多个炉室(优先使用小炉室)
    return allocateProgramToMultipleChambers(programData, ovens);
}

// 将整个程序分配到指定炉室
function allocateWholeProgram(programData, chamber) {
    const program = programData.products[0].program;
    chamber.program = program;
    
    for (const product of programData.products) {
        if (product.remainingTrays > 0) {
            const traysToAdd = product.remainingTrays;
            const layersToAdd = traysToAdd * product.layersPerTray;
            
            chamber.products.push({
                id: product.id,
                name: product.name,
                trays: traysToAdd,
                layers: layersToAdd,
                program: program
            });
            chamber.usedLayers += layersToAdd;
            product.remainingTrays = 0;
        }
    }
    return true;
}

// 分散分配到多个炉室
function allocateProgramToMultipleChambers(programData, ovens) {
    let anyAllocated = false;
    const program = programData.products[0].program;
    
    // 优先分配到小炉室
    for (const product of programData.products) {
        if (product.remainingTrays <= 0) continue;
        
        // 先尝试小炉室
        for (const oven of ovens) {
            const smallChamber = oven.chambers.find(c => c.maxLayers === 5);
            if (smallChamber && (smallChamber.program === program || smallChamber.program === null)) {
                const allocated = tryAllocateToChamber(product, smallChamber, program);
                if (allocated) anyAllocated = true;
                if (product.remainingTrays <= 0) break;
            }
        }
        
        // 再尝试大炉室
        for (const oven of ovens) {
            const largeChamber = oven.chambers.find(c => c.maxLayers === 10);
            if (largeChamber && (largeChamber.program === program || largeChamber.program === null)) {
                const allocated = tryAllocateToChamber(product, largeChamber, program);
                if (allocated) anyAllocated = true;
                if (product.remainingTrays <= 0) break;
            }
        }
    }
    return anyAllocated;
}

// 尝试将产品分配到指定炉室
function tryAllocateToChamber(product, chamber, program) {
    const availableLayers = chamber.maxLayers - chamber.usedLayers;
    const maxPossibleTrays = Math.floor(availableLayers / product.layersPerTray);
    const traysToAdd = Math.min(maxPossibleTrays, product.remainingTrays);
    
    if (traysToAdd > 0) {
        const layersToAdd = traysToAdd * product.layersPerTray;
        
        chamber.products.push({
            id: product.id,
            name: product.name,
            trays: traysToAdd,
            layers: layersToAdd,
            program: program
        });
        chamber.usedLayers += layersToAdd;
        chamber.program = program;
        product.remainingTrays -= traysToAdd;
        return true;
    }
    return false;
}

function initializeOvens() {
    const ovens = [];
    for (let i = 0; i < ovenConfig.ovenCount; i++) {
        ovens.push({
            id: i + 1,
            chambers: [
                { id: 1, maxLayers: ovenConfig.chamberLayers[0], usedLayers: 0, program: null, products: [] },
                { id: 2, maxLayers: ovenConfig.chamberLayers[1], usedLayers: 0, program: null, products: [] }
            ]
        });
    }
    return ovens;
}

// 更新每个程序的总层数需求
function updateProgramLayers(programs) {
    Object.keys(programs).forEach(program => {
        programs[program].totalLayers = programs[program].products
            .reduce((sum, p) => sum + (p.remainingTrays * p.layersPerTray), 0);
    });
}

// 检查是否还有未分配的产品
function checkUnallocated(programs) {
    return Object.keys(programs).some(
        program => programs[program].totalLayers > 0
    );
}

// 显示多批次排产结果
function displayBatchResults(batches, requirements) {
    const outputContainer = document.getElementById('output-results');
    outputContainer.innerHTML = '';
    
    // 显示总需求 (保持不变)
    const summaryDiv = document.createElement('div');
    summaryDiv.className = 'summary-section';
    summaryDiv.innerHTML = '<h3>生产需求汇总</h3>';
    
    const table = document.createElement('table');
    table.innerHTML = `
        <tr>
            <th>商品名称</th>
            <th>总需求量</th>
            <th>总托盘数</th>
            <th>总占用层数</th>
        </tr>
    `;
    
    requirements.forEach(product => {
        table.innerHTML += `
            <tr>
                <td>${product.name}</td>
                <td>${product.quantity}</td>
                <td>${product.traysNeeded}</td>
                <td>${product.layersNeeded}</td>
            </tr>
        `;
    });
    
    summaryDiv.appendChild(table);
    outputContainer.appendChild(summaryDiv);
    
    // 显示每批次结果 - 修改为横向排列
    batches.forEach((batch, index) => {
        const batchDiv = document.createElement('div');
        batchDiv.className = 'batch-result';
        batchDiv.innerHTML = `<h3>第 ${index + 1} 批次</h3>`;
        
        const ovensDiv = document.createElement('div');
        ovensDiv.className = 'batch-ovens';
        
        batch.forEach(oven => {
            const ovenDiv = document.createElement('div');
            ovenDiv.className = 'oven-result';
            ovenDiv.innerHTML = `<h4>烤箱 ${oven.id}</h4>`;
            
            oven.chambers.forEach(chamber => {
                const chamberDiv = document.createElement('div');
                chamberDiv.className = 'chamber-result';
                
                if (chamber.products.length === 0) {
                    chamberDiv.innerHTML = `<strong>炉室 ${chamber.id}</strong>: 空闲`;
                } else {
                    let content = `<strong>炉室 ${chamber.id}</strong> (程序${chamber.program}, 共计 ${chamber.usedLayers}/${chamber.maxLayers}层):<br>`;
                    chamber.products.forEach(product => {
                        content += `${product.name}: ${product.trays}盘 (${product.layers}层)<br>`;
                    });
                    chamberDiv.innerHTML = content;
                }
                
                ovenDiv.appendChild(chamberDiv);
            });
            
            ovensDiv.appendChild(ovenDiv);
        });
        
        batchDiv.appendChild(ovensDiv);
        outputContainer.appendChild(batchDiv);
    });
}